package com.xqh.admin.controller.ques;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xqh.admin.commom.BaseController;
import com.xqh.base.cache.RedisService;
import com.xqh.base.common.ModifyCommonDto;
import com.xqh.base.mybatis.page.Page;
import com.xqh.base.pool.ThreadPoolUtils;
import com.xqh.base.util.CompressUtils;
import com.xqh.base.util.excel.ExcelExportUtil;
import com.xqh.base.util.excel.ExcelReader;
import com.xqh.base.util.id.IdWorker;
import com.xqh.base.util.response.RespMsg;
import com.xqh.base.util.serializer.ObjectUtils;
import com.xqh.base.util.word.SpecialCharUtils;
import com.xqh.common.Global;
import com.xqh.common.fastdfs.FastDFSFile;
import com.xqh.entity.ques.Vocabulary;
import com.xqh.service.ques.VocabularyService;
import com.xqh.spider.SpiderWordThread;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 词汇管理
 */
@Controller
@RequestMapping(value = "/vocab")
public class VocabularyController extends BaseController {

    @Autowired
    private VocabularyService vocabularyService;

    @Autowired
    private RedisService redisService;

    @RequestMapping(value = "list", method = RequestMethod.GET)
    public ModelAndView list(){
        return new ModelAndView("ques/vocab/vocab_list");
    }

    @RequestMapping(value = "listData", method = RequestMethod.GET)
    public @ResponseBody
    Page<?> listData(Page page, Vocabulary vocabulary){
        vocabularyService.findByPage(page, ObjectUtils.changeToMap(vocabulary));
        return page;
    }

    @RequestMapping(value = "modifyData", method = RequestMethod.POST)
    public @ResponseBody RespMsg<?> modifyData(ModifyCommonDto dto){
       try {
           vocabularyService.modifyData(dto);
       }catch (Exception e){
           return RespMsg.failResp(e.getMessage());
       }
       return RespMsg.successResp();
    }

    /**
     * 上传词汇
     * @param file
     * @return
     */
    @RequestMapping(value = "uploadVocab")
    public @ResponseBody RespMsg<?> uploadVocab(@RequestParam("file") MultipartFile file){

        List<String[]> list = ExcelReader.getExcelData(file, 1);
        List<String> excelList = new ArrayList<>();
        for(String[] array:list){
            if(null != array && StringUtils.hasText(array[0])){
                String word = SpecialCharUtils.removeSpecialChar(array[0].trim());
                excelList.add(word);
            }
        }
        List<String> wordList =vocabularyService.filterUnSpiderWords(excelList);

        List<FutureTask<Vocabulary>> fuList = new ArrayList<>();
        for(String word : wordList){
               FutureTask<Vocabulary> futureTask = new FutureTask<>(new SpiderWordThread(word));
               ThreadPoolUtils.submit(futureTask);
               fuList.add(futureTask);
        }
        for(FutureTask<Vocabulary> future:fuList){
            try {
                Vocabulary vocab = future.get();
                VocabularyInsertThread vit = new VocabularyInsertThread(vocab, vocabularyService);
                ThreadPoolUtils.execute(vit);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        return RespMsg.successResp(new FastDFSFile("success"));
    }

    @RequestMapping(value = "exportTmp")
    public @ResponseBody RespMsg exportTmp(@RequestParam("file") MultipartFile file){
        String code = setData2Redis(file);
        return RespMsg.successResp(new FastDFSFile(code));
    }


    public String setData2Redis(MultipartFile file){
        List<String[]> list = ExcelReader.getExcelData(file, 1);
        List<String> excelList = new ArrayList<>();
        for(String[] array:list){
            if(null != array && StringUtils.hasText(array[0])){
                String word = SpecialCharUtils.removeSpecialChar(array[0].trim());
                excelList.add(word);
            }
        }
        String code = IdWorker.getStringCode();
        redisService.setString(code, JSON.toJSONString(excelList), 60);
        return code;
    }


    /**
     * 导出 对应例句
     */
    @RequestMapping(value = "exportExcel",method = RequestMethod.POST)
    public void exportExcel(String code){
        List<String> excelList = JSONArray.parseArray(redisService.getString(code),String.class);
        Map<String,Vocabulary> voMap = new HashMap<>();
        List<Vocabulary> voList = null;
        if(!CollectionUtils.isEmpty(excelList)){
            Map<String,Object> map = new HashMap<>();
            map.put("wordList", excelList);
            voList= vocabularyService.findByBiz(map);

            for(Vocabulary vo:voList){
                if(!Vocabulary.EMPTY.equals(vo.getExampleSentence())){
                    //有例句 信息
                    JSONArray array = JSONArray.parseArray(vo.getExampleSentence());
                    if(null != array && array.size()>0){
                        JSONObject obj = (JSONObject) array.get(0);
                        vo.setEgSentence(obj.getString("sentence"));
                        vo.setEgTranslation(obj.getString("translation"));
                    }
                }
                if(!Vocabulary.EMPTY.equals(vo.getEnExplain())){
                    //有英英释义
                    JSONArray array = JSONArray.parseArray(vo.getEnExplain());
                    if(null != array && array.size()>0){
                        for(Object json:array){
                            JSONObject obj = (JSONObject) json;
                            if(StringUtils.hasText(vo.getEgEnExplain())){
                                vo.setEgEnExplain(vo.getEgEnExplain().concat("[").concat(obj.getString("explain")).concat("]"));
                            }else{
                                vo.setEgEnExplain("[".concat(obj.getString("explain")).concat("]"));
                            }
                        }
                    }
                }
                voMap.put(vo.getText(),vo);
            }
        }else {
            voList = new ArrayList<>();//导出空文件
        }

        String[] headers={"单词","音标--英","音标--美","翻译","例句","例句翻译", "英英释义"};
        String[] properties={"text","ukPhonetic","usPhonetic","translationJson","egSentence","egTranslation","egEnExplain"};
        List<Vocabulary> outList = new ArrayList<>();
        for(String word:excelList){
            if(voMap.containsKey(word)){
                outList.add(voMap.get(word));
            }else{
                Vocabulary vocabu = new Vocabulary();
                vocabu.setText(word);
                outList.add(vocabu);
            }
        }
        ExcelExportUtil.down(getRequest(),getResponse(),ExcelExportUtil.export(headers, properties, outList,false),"词汇数据导出");
    }

    @RequestMapping(value = "exportAudioTmp")
    public @ResponseBody RespMsg exportAudioTmp(@RequestParam("file") MultipartFile file){
        String code = setData2Redis(file);
        return RespMsg.successResp(new FastDFSFile(code));
    }

    /**
     * 导出 对应例句
     */
    @RequestMapping(value = "exportAudio",method = RequestMethod.POST)
    public void exportAudio(String code){
        List<String> excelList = JSONArray.parseArray(redisService.getString(code),String.class);
        List<Vocabulary> voList = null;
        if(!CollectionUtils.isEmpty(excelList)){
            Map<String,Object> map = new HashMap<>();
            map.put("wordList", excelList);
            voList= vocabularyService.findByBiz(map);
        }else {
            voList = new ArrayList<>();
        }

        String filePath = Global.getConfig("vocabulary.path");
        String _code = IdWorker.getStringCode();
        String tmpPath = filePath+ File.separator+ _code;
        String uk_path = tmpPath+File.separator+"uk";
        String us_path = tmpPath+File.separator+"us";
        File file=new File(tmpPath);
        file.mkdir();
        try {
            for(Vocabulary voca:voList){
                if(StringUtils.hasText(voca.getAudioUrl())){
                    File uk_resource = new File(filePath+File.separator+"uk"+File.separator+voca.getAudioUrl());
                    File us_resource = new File(filePath+File.separator+"us"+File.separator+voca.getAudioUrl());
                    if(uk_resource.exists()){
                        File uk_target = new File(uk_path+File.separator+voca.getAudioUrl());
                        FileUtils.copyFile(uk_resource, uk_target);
                    }
                    if(us_resource.exists()){
                        File uk_target = new File(us_path+File.separator+voca.getAudioUrl());
                        FileUtils.copyFile(us_resource, uk_target);
                    }
                }
            }
            CompressUtils.zipFile(tmpPath.concat(".zip"), tmpPath);
            File zip =  new File(tmpPath.concat(".zip"));
            ExcelExportUtil.down(getRequest(), getResponse(),zip ,"音频下载");
            FileUtils.deleteDirectory(file);
            zip.delete();
        } catch (IOException e) {
            logger.error("",e);
        }
    }

    /**
     * 保存数据
     */
    public static class VocabularyInsertThread implements Runnable{

        private VocabularyService vocabularyService;

        private Vocabulary vocabulary;

        public VocabularyInsertThread(Vocabulary vocabulary, VocabularyService vocabularyService){
            this.vocabulary=vocabulary;
            this.vocabularyService=vocabularyService;
        }

        @Override
        public void run() {
           vocabularyService.saveData(vocabulary);
        }
    }


}
